package com.dylan.历史.java8.StreamAPI;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by Dylan on 2018/7/23.
 */
public class Stream处理4_收集 {

    public static void main(String[] args) {
        // 收集到数组
        String[] arr = getWords().toArray(String[]::new);

        /**
         * 收集到Set
         * 参数1:创建目标实例的方法
         * 参数2:将元素添加到目标中的方法
         * 参数3:将两个对象整合到一起的对象
         */
        HashSet<String> set1 = getWords().collect(HashSet::new, HashSet::add, HashSet::addAll);

        // 使用工厂方法
        Set<String> set2 = getWords().collect(Collectors.toSet());
        TreeSet<String> set3 = getWords().collect(Collectors.toCollection(TreeSet::new));
        List<String> list1 = getWords().collect(Collectors.toList());

        // 字符串连接
        String str1 = getWords().collect(Collectors.joining());
        String str2 = getWords().collect(Collectors.joining(","));
        String str3 = Stream.of(1, 2, 3, 4, 5, 6).map(Object::toString).collect(Collectors.joining(","));

        // 统计数值
        double num1 = Stream.of(1, 2, 3, 4, 5, 6).collect(Collectors.summarizingInt(Integer::intValue)).getAverage();
        double num2 = Stream.of(1, 2, 3, 4, 5, 6).collect(Collectors.summarizingInt(Integer::intValue)).getMax();
        long num3 = Stream.of(1, 2, 3, 4, 5, 6).collect(Collectors.summarizingInt(Integer::intValue)).getSum();

        // foreach处理. forEachOrdered() 方法会按流的顺序进行执行,这样会放弃并行计算
        Stream.of(5, 4, 1, 2, 3, 6).parallel().forEach(System.out::println);
        Stream.of(5, 4, 1, 2, 3, 6).parallel().forEachOrdered(System.out::println);
    }

    private static Stream<String> getWords() {
        return Pattern.compile("[\\P{L}]+").splitAsStream("Ramesses VI was the fifth ruler of the Twentieth Dynasty of Egypt. He succeeded Ramesses V and reigned for about eight years in the mid-to-late 12th century BC before dying in his forties. Egypt lost control of its last strongholds in Canaan around the time of his reign. The pharaoh's power waned in Upper Egypt during his rule, while the high priest of Amun, Ramessesnakht, was turning Thebes in Upper Egypt into the religious capital and a second center of power on par with Pi-Ramesses in Lower Egypt, where the pharaoh resided. He was fond of cult statues of himself; more are known to portray him than any other Twentieth-Dynasty king after his father, Ramesses III. He usurped KV9, a tomb in the Valley of the Kings planned by and for Ramesses V, and had it enlarged and redecorated for himself. His mummy lay untouched for fewer than 20 years before pillagers damaged it.");
    }
}
